import MessageHandlers from "./MessageHandlers"

import {move} from "./msg/msg"


export default class WebSocketClient {
    address: string;
    webSocket: WebSocket;
    public constructor(addr: string) {
        this.address = addr;

    }
    public start() {
        this.webSocket = new WebSocket(this.address);
        this.socketBindEvent();
    }
    socketBindEvent() {
        this.webSocket.onopen = this.onOpen.bind(this);
        this.webSocket.onmessage = this.onMessage.bind(this);
        this.webSocket.onerror = this.onError.bind(this);
        this.webSocket.onclose = this.onClose.bind(this);
    }
    onOpen(ev: Event) {
        console.log("webSocket连接建立成功... " + "服务端address: " + this.address);
        //连接成功 发送消息
        let testObj = {
            type: "getUserInfo"
        }
        let pos = {
            x:1,
            y:2
        }
        let msg = move.C2S_SyncPosition.create(pos)
        // this.sendData(JSON.stringify(testObj));
        this.sendData(move.C2S_SyncPosition.encode(msg).finish());

    }
    onMessage(event: MessageEvent) {
        console.log("收到消息：", event.data);
        let data = JSON.parse(event.data)

        let handlers = MessageHandlers.instance()
        handlers[data.type](data)

    }
    onError(ev: Event) {
        console.log(ev);

    }
    onClose(ev: CloseEvent) {
        console.log("链接关闭了");
    }
    sendData(data: string | ArrayBufferLike | Blob | ArrayBufferView) {
        this.webSocket.send(data)
    }
}